<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('尾程对账单')" />
	<th:block th:include="include :: businessCSS" />
	<style>
        .main-content{position: relative;}
        .topbtns{position:fixed;top: 0;width: 100%;z-index: 9999;background-color: #fff;}
		.preservationBtn{padding: 10px;margin: 0;position: fixed;top: 0;z-index: 9999;background: #fff;width: 100%;}
		.preservationBtn input{font-size: 16px;background-color: rgb(80, 138, 238);color: #fff;border: none;padding: 5px 30px;border-radius: 5px;cursor: pointer;}
		/* .layui-border-box{height: 350px !important;}
		.layui-table-body{height: 240px !important;} */
		.layui-table-tool-temp{padding-right: 30px;}
        .getDetailUpload,.getDetailUpload2{cursor: pointer;}
        .layui-table-tool-self{display: none;}
        .listext th{background:#eee;color:#3366cc;}
        .listext th,.listext td{border:solid 1px #ddd;text-align:left;padding:10px;font-size:14px;}
        .importTable{empty-cells:show;border-collapse:collapse;border-spacing:0;}
	</style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
	<div class="main-content">
	<form class="layui-form head-form">
        <div class="north">
            <th:block th:include="include :: business_btn" />
            <th:block th:include="include :: business_tp2('top')" />
        </div>
        <div style="width: 100%;height: 10px;background: #f6f6f6;"></div>
        <div>
            <table class="layui-hide" id="mjdhtable" lay-filter="mjtable"></table>
            <script type="text/html" id="zjtoolbar">
                <div style="padding: 16px;display: flex;justify-content: space-between;">
                    <div  style="font-weight: 700;font-size: 18px;">海外尾程单信息</div>
            		<div>
                        <button class="layui-btn layui-btn-normal dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="addbtn" id="btn-sh">新增</button>
                        <button class="layui-btn layui-btn-normal dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" onclick="importBtn()" lay-event="import" id="import">物流商对账单导入</button>
                        <button class="layui-btn layui-btn-normal dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="cutbtn" id="cutbtn">系统/对账金额转换</button>
                        <button class="layui-btn layui-btn-danger dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="mjbtn_save" id="mjbtn-sh">删除</button>
            		</div>
            	</div>
            </script>
        </div>
        <div style="width: 100%;height: 10px;background: #f6f6f6;"></div>
        <div>
            <table class="layui-hide" id="xqdhtable" lay-filter="xqtable"></table>
            <script type="text/html" id="xqtoolbar">
                <div style="padding: 16px;display: flex;justify-content: space-between;">
                    <div  style="font-weight: 700;font-size: 18px;">海外尾程单详情</div>
                </div>
            </script>
        </div>
        <th:block th:include="include :: pageFooter" /> 
    </form>
	</div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />
<th:block th:include="include :: inlineJS" />
<th:block th:include="include :: searchJS" />
<script th:src="@{/dhecp/js/queryCondition.js}"></script>
<th:block th:include="listinclude :: list-templeat" />

<!-- 导入明细 -->
<div id="iTable" class="display_no">
    <table class="importTable listext" data-resizable-columns-id="demo-table">
        <tbody id="itbody"></tbody>
    </table>
</div>


<script th:inline="javascript">
	/*<![CDATA[*/
	var prefix = ctx + "logstics/fbaLogisticsReconcile",
    	prefix2 = ctx + "base/company";

	var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
	var fieldsHiddenList = [[${fieldsHiddenList}]];
	var moduleTable = [[${moduleTable}]];
	var enableEdit = [[${enableEdit}]];
	//导入字段
    var importFields =[[${importFields}]];
    //商品表格基础信息
	var gridColumns = [[${gridColumns}]];
	var gridColumnsZJ = [[${gridColumnsZJ}]];
	//判断是取对账数据还是付款数据  0 系统| 1 对账
    var isf = 0;
    //发货标题
    var tablecolsFh=tablecolsFh();

    // 商品列表数据
    var List=[[${List}]];
    //子件列表数据
    var sonList=[[${sonList}]];
    var element,thStr;
    var fieldWidth = {},		//导入列表字段宽度
        filedRequired = {},		//导入列表必填字段
        dateFiled = [],			//导入列表日期字段
        hasNull = false;		//导入数据必填字段有空值
    $.each(gridColumnsZJ.dictionaryForPageFieldList,function(i,v){
        fieldWidth[v.fields] = v.fieldFrontWidth
        if(v.fieldFrontRequired)filedRequired[v.fields] = v.fieldName;
        if(v.fieldFrontType == 't_date')dateFiled.push(v.fields);
    })

    var tablecols1=[
        {type: 'numbers', fixed: 'left'}
        , {type: 'checkbox'}
        ,{align: 'center',field: 'bid', title: '海外尾程单号', width: 160}
        ,{align: 'center',field: 'stockOutCode', title: '海外尾程出库单号', width: 150}
        ,{align: 'center',field: 'shipmentid', title: 'FBA编号', width: 120}
        ,{align: 'center',field: 'vgsjc', title: '公司简称', width: 100}
        ,{align: 'center',field: 'shopName', title: '网店名称', width: 100}
        ,{align: 'center',field: 'launchwarehouse', title: '发出仓库', width: 100}
        ,{align: 'center',field: 'destinationfulfillmentcenterid', title: '目的仓库', width: 100}
        ,{align: 'center',field: 'countrycode', title: '国家', width: 100}
        ,{align: 'center',field: 'city', title: '城市', width: 100}
        ,{align: 'center',field: 'weightreal', title: '实重', width: 100}
        ,{align: 'center',field: 'weightvol', title: '抛重', width: 100}
        ,{align: 'center',field: 'weightcal', title: '计重', width: 100}
        ,{align: 'center',field: 'numbox', title: '箱数', width: 100}
        ,{align: 'center',field: 'numcommodity', title: '商品数量', width: 100}
        ,{align: 'center',field: 'lastvoyagechargext', title: '尾程费(系统)',totalRow:true, width: 120}
        ,{align: 'center',field: 'lastvoyagechargedz', title: '尾程费(对账)',totalRow:true, width: 120}
        ,{align: 'center',field: 'lastvoyagechargefk', title: '尾程费(付款)',totalRow:true,edit:'text', width: 120}
        ,{align: 'center',field: 'reconciliation', title: '对账情况', width: 100}
        ,{align: 'center',field: 'reconciliationst', title: '对账说明',edit:'text', width: 100}
        ,{align: 'center',field: 'bid', title: '海外尾程单号',edit:'text', width: 100,hide: true}
        ,{align: 'center',field: 'guid', title: '海外尾程guid',edit:'text', width: 100,hide: true}
    ]


   

	var $,layer,form,table,nid,noTable;

    layui.use(['laydate','form','layer','jquery','util','element','upload','table'], function () {
        $ = layui.$,layer = layui.layer,form = layui.form,laydate = layui.laydate,util = layui.util,element=layui.element,upload = layui.upload,table = layui.table;
        beforeInit();//表单初始化之前的动作集合
		//初始化操作
		headcom3()
        nid=$('#nid').val()
         // 保存按钮事件变化
        $(function(){
           $('.tp-save').attr('onclick','')
           $('.tp-save').attr('lay-filter','btn-edit')
           $('.tp-save').attr('lay-submit',true)
        })

        
        // 保存操作
        form.on('submit(btn-edit)', function(data){
            var is_return = false//是否中断保存
            if (listData1.length == 0){
                layer.msg("海外尾程单不允许为空,请核实后在操作！");
                return;
            }else {
                listData1.map((v,i)=>{
                    if(is_return) return;
                    if (v.lastvoyagechargedz == null || v.lastvoyagechargedz == ""){
                        is_return = true;
                        layer.msg("尾程费(对账)不允许为空,请核实后在操作！");
                        return;
                    }
                    if (v.lastvoyagechargefk == null || v.lastvoyagechargefk == ""){
                        is_return = true;
                        layer.msg("尾程费(付款)不允许为空,请核实后在操作！");
                        return;
                    }
                    if (v.reconciliation == "对账错误"){
                        if(v.reconciliationst == "" || v.reconciliationst == null){
                            is_return = true;
                            layer.msg("对账情况:对账错误,对账说明不允许为空,请核实后在操作！");
                            return;
                        }

                    }
                })
            }
            if(is_return) return;
            $.modal.loading("正在处理中，请稍后...");
            $.post("/storage/hwFinalstatement/editpost",{infoMap:JSON.stringify(data.field),infoItems:JSON.stringify(listData1),sonData:JSON.stringify(listData1)},function(res){
                $.modal.closeLoading()
			 	layer.msg(res.msg);
                if(res.code == 0){
                   window.location.href = '/storage/hwFinalstatement/edit?nid=' + res.data;
                }
	        });
        });

        //单击选中行
        table.on('rowDouble(mjtable)', function(obj){
            $.get('/storage/hwTailprogram/sonlist',{code:obj.data.bid,guid:obj.data.pguid},function(res){
                var datalist=res.data.sonList;
                var cols=[res.data.gridColumns.gridBody];
                var totalRow=res.data.gridColumns.totalRow;
                if (res.data.hwTailprogramApi.creationMethod == '手动'){
                    cols = tablecolsFh;
                } else {
                    cols = tablecolsZD();
                    //根据coleSize编辑出多少个箱子
                    for (let i = 0; i < obj.data.numBox; i++) {
                        let  tableData = {
                            "align": "center",
                            "field": "numRealityDeliver"+(i+1),
                            "title": "箱子"+(i+1),
                            "width": 95,
                        }
                        cols[0].push(tableData);
                    }

                    //将箱子数据赋值
                    if (obj.data.numBox != 0){
                        for (let i = 0; i < datalist.length; i++) {
                            let ss = datalist[i].boxList.slice(1,datalist[i].boxList.length-1)
                            let aa =  ss.split(",");
                            for (let j = 0; j < aa.length; j++) {
                                let numRe = 'numRealityDeliver'+(j+1)
                                datalist[i][numRe] = aa[j]==0?"":aa[j]
                            }
                        }
                    }
                }
                $.tablelist.init({
                    elem: '#xqdhtable'
                    ,data:datalist
                    ,where: getWherestr()
                    , page: false
                    , even: true
                    , limit: 10000
                    , totalRow: false
                    , cols: cols
                    , toolbar: '#xqtoolbar'
                    , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
                    , height: '320'
                    , done: function (res, curr, count) {
                        listData2 = table.cache.xqdhtable;//每次重载都赋值更新表缓存
                    },success:function(a,b,c){
                        // console.log(a,b,c,9999)
                    }
                });
            })
        });

        var listData1=List ?List:[]
        var listData2=sonList ?sonList:[]
        // 初始化表格
        $.tablelist.init({
            elem: '#mjdhtable'
            ,data: listData1
            , page: false
            , even: true
            , limit: 10000
            , totalRow: true
            , cols: [tablecols1]
            , toolbar: '#zjtoolbar'
            , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            , height: '320'
            , done: function (res, curr, count) {
                listData1 = table.cache.mjdhtable;//每次重载都赋值更新表缓存
            },success:function(a,b,c){
                    // console.log(a,b,c,9999)
            }
        });

        $.tablelist.init({
            elem: '#xqdhtable'
            ,data: []
            , page: false
            , even: true
            , limit: 10000
            , totalRow: false
            , cols: tablecolsFh
            , toolbar: '#xqtoolbar'
            , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            , height: '320'
            , done: function (res, curr, count) {
                listData2 = table.cache.xqdhtable;//每次重载都赋值更新表缓存
            },success:function(a,b,c){
                // console.log(a,b,c,9999)
            }
        });

        //监听单元格编辑
        table.on('edit(mjtable)', function(obj){
            listData1.map((n,m)=>{
                upReconciliation(n)
            })
            table.reload('mjdhtable', {data: listData1});
        });



        //商品表格操作
        table.on('toolbar(mjtable)', function (obj) {
            var selectedObject=""
            sessionStorage.setItem('mjdata',JSON.stringify(table.cache.mjdhtable))
            table.cache.mjdhtable.map((v,i)=>{
                if(selectedObject){
                    selectedObject+=','+v.shipmentid
                }else{
                    selectedObject+=v.shipmentid
                }
            })
            switch (obj.event) {
                case 'addbtn':
                if (!$('#tailprogram').val()){
                    layer.msg("尾程方式为空,不允许新增！");
                    return;
                }
                if (!$('#channelcode').val()){
                    layer.msg("渠道代码为空,不允许新增！");
                    return;
                }
			    layer.open({
                	type: 2,
                	area: [($(window).width() - 200)+'px', ($(window).height() - 100)+'px'],
                	fix: false,//不固定
                	offset: '10%',//距离顶部
                	maxmin: true,//最大最小化
                	shade: 0.3,//遮罩
                	title: '尾程单信息',
                	content: "/storage/hwFinalstatement/select2?pagetype=checkbox&by=direct&fmoduleTable="+"HW_FINALSTATEMENT"+"&selectedObject="+selectedObject+"&tailprogram="+$('#tailprogram').val()+"&channelcode="+$('#channelcode').val()+"&bid="+$('#bid').val(),
                	btn: ['确定', '取消'],
                	shadeClose: true,// 弹层外区域关闭
                	yes: function(index, layero){
						var res = window["layui-layer-iframe" + index].callbackdata();
				        if(res.length > 0){
                            $.each(res,function(i,v){
                                v.lastvoyagechargext = v.lastvoyagecharge
                                v.lastvoyagechargefk = v.lastvoyagecharge
                                v.reconciliation = '无'
                                upReconciliation(v)
				        	})
							layer.closeAll();
                            var mjdata=sessionStorage.getItem('mjdata')
                            if(mjdata){
                                mjdata=JSON.parse(mjdata)
                                let newall=[]
                                let endData = [];
                                var isdata=false
                                for (let i = 0; i < res.length; i++) {
                                    var isdata=false
                                    if (newall.indexOf(res[i].shipmentid) === -1) {
                                        for (let n = 0; n < mjdata.length; n++) {
                                            if (newall.indexOf(res[i].shipmentid) === -1) {
                                                if(res[i].shipmentid==mjdata[n].shipmentid){
                                                   isdata=true
                                                   endData.push(mjdata[n]);
                                                   newall.push(mjdata[n].shipmentid);
                                                }
                                            }
                                        }
                                        if(!isdata){
                                            endData.push(res[i]);
                                            newall.push(res[i].shipmentid);
                                        }
                                    }
                                }
                                table.reload('mjdhtable', {data:endData});
                            }else{
                                table.reload('mjdhtable', {data:res});
                            }
				        }else{
                            layer.msg("请选择数据");
                        }
                	}
                });

                   break;
    
                case 'mjbtn_save':
                    var objdata=table.checkStatus('mjdhtable')
                    objdata=objdata.data
                    listData1= table.cache.mjdhtable;
                    listData2 = table.cache.zjdhtable;
                    if(objdata.length>0){
                        objdata.forEach(item => {
                            listData1 = listData1.filter(items => items.shipmentid!= item.shipmentid);
                        });
                        table.reload('mjdhtable', {data:listData1});
                        table.reload('xqdhtable', {data:[]});
                    }else{
                        layer.msg("请选择数据");
                    }
                    break;
                case 'cutbtn':
                    var msg = isf == 0 ? "是否切换至对账数据?" : "是否切换至系统数据?";
                    $.modal.confirmCom(msg, function (result) {
                        isf = isf == 0 ? 1 : 0;
                        listData1 = table.cache.mjdhtable;
                        if (listData1.length > 0) {
                            listData1.forEach(v => {
                                if (isf == 0) {
                                    v.lastvoyagechargefk = v.lastvoyagechargext
                                } else {
                                    v.lastvoyagechargefk = v.lastvoyagechargedz
                                }
                                upReconciliation(v)
                            });
                            table.reload('mjdhtable', {data: listData1});
                            layer.closeAll();
                        } else {
                            layer.msg("请新增数据");
                        }
                    })
                    break;
            };
        });
    });

    function  importBtn(){
        if (importFields) {
            thStr = '<tr><th><div style="width:30px;">序号</div></th>';
            $.each(importFields, function (i, val) {
                fieldWidth[val] = fieldWidth[val] ? fieldWidth[val] : 100;	//默认宽度100px
                thStr += '<th><div style="width:' + fieldWidth[val] + 'px;">' + i + '</div></th>';
            })
            thStr += '</tr>';
            layer.open({
                type: 1,
                area: ['400px', '230px'],
                fix: false,
                offset: '10%',
                maxmin: true,
                shade: 0.3,
                title: '导入',
                content: `
						<form enctype="multipart/form-data" class="mt20 mb10">
							<div class="col-xs-offset-1">
							<input type="file" id="file" name="file"/>
							<div class="mt10 pt5">
							<a onclick="$.tablelist.importTemplate('/storage/hwFinalstatement/template?')" class="btn btn-default btn-xs"><i class="dhicon dh-file-excel-o"></i> 下载模板</a>
							</div>
							<font color="red" class="pull-left mt10">提示：仅允许导入“xls”或“xlsx”格式文件！</font>
							</div>
						</form>
												`,
                btn: ['<i class="dhicon dh-check"></i> 导入', '<i class="dhicon dh-remove"></i> 取消'],
                shadeClose: true,
                zIndex: 1000,
                btn1: function (index, layero) {
                    var file = layero.find('#file');
                    if (!file[0]['value']) {
                        layer.msg("请选择文件！");
                        return false;
                    }
                    var imRes = importListExcel(file[0], importFields,'hwTailprogramApi');
                }
            });
        } else {
            $.modal.alertWarning("后台未返回导入模板对象！");
        }
    }

    /*批量请求导入数据
     *tobj：导入数据对象
     *startNum：从第几条开始导入
     *oneImportNum：每次导入条数
     *allImportNum：总数据量
     *times：导入次数
     */
    function eachImport(tobj,startNum, oneImportNum, allImportNum, times, timeNum){
        var importObj = [];
        for(var i = startNum; i < allImportNum; i++){
            importObj.push(tobj[i]);
        }
        if (importObj.length ==0){
            layer.msg("导入数据为空,请核实后在操作!");
            showloadings(false);
            return;
        }
        $.ajaxSettings.async = false;
        listData1= table.cache.mjdhtable;
        showloadings(false);
        if(listData1.length>0){
            listData1.forEach(item => {
                let data = importObj.filter(items => items.shipmentid== item.shipmentid);
                if (data.length != 0){
                    item.lastvoyagechargedz = data[0].lastvoyagechargedz
                    upReconciliation(item)
                }
            });
            layer.msg("导入成功")
            setTimeout(function(){
                sessionStorage.setItem(moduleTable+'checkdata','')
                layer.closeAll();
                table.reload('mjdhtable', {data:listData1});
            }, 1000);
        }else{
            layer.msg("请新增尾程单数据!");
        }
    }

    //判断对账状态
    function upReconciliation(v){
        if (Number(v.lastvoyagechargefk) - Number(v.lastvoyagechargext) <= 0){
            v.reconciliation = "对账正确"
        } else {
            v.reconciliation = "对账错误"
        }
    }

    /**
     * 回调弹框事件
     */
    function getMoreAfter(fieldsList,fields,tindex,fieldName,fieldSearchType,isSearch,isLayer,res) {//弹出框赋值回调
        if(fields=='tailprogram' || fields=='channelcode'){
            listData1 = [];
            table.reload('mjdhtable', {data:listData1});
        }
    }

</script>

</body>
</html>